﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using OAuthAccess;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Xml.Linq;

namespace SimpleTwitterAccessSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //Twitter don't support 100Continue.
            ServicePointManager.Expect100Continue = false;

            //if you rewrite the following two strings,this sample will be available. 
            string twitterConsumerKey = "twitter consumer key";
            string twitterConsumerSecret = "twitter consumer secret";

            /*
             * Uses OAuthAuthorizationService class until Access Token is obtained.
             */

            Consumer consumer = new Consumer(
                twitterConsumerKey,
                twitterConsumerSecret);

            //Get Request Token
            RequestToken requestToken = OAuthAuthorizationService.GetRequestToken(
                consumer,
                "http://twitter.com/oauth/request_token",
                "http://twitter.com/",
                HttpMethodType.Get).Token as RequestToken;

            //It is necessary you have authenticated to user. 
            Process.Start(OAuthAuthorizationService.GetUserAuthorizationURL(
                "http://twitter.com/oauth/authorize",
                requestToken));

            //You have inputted to user.
            Console.Out.WriteLine("Please input verify...");

            string verifier = Console.In.ReadLine().TrimEnd('\r', '\n');

            //Get AccessToken

            TokenResponse accessTokenResponse =  OAuthAuthorizationService.GetAccessToken(
                consumer,
                "http://twitter.com/oauth/access_token",
                "http://twitter.com/",
                requestToken,
                verifier,
                HttpMethodType.Post);

            AccessToken accessToken = accessTokenResponse.Token as AccessToken;

            string user_id = (from p in accessTokenResponse.AdditionalParameters 
                             where p.Key == "user_id" 
                              select p).First().Value;

            string screen_name = (from p in accessTokenResponse.AdditionalParameters
                                  where p.Key == "screen_name"
                                  select p).First().Value;

            Console.WriteLine("Screen_Name : " + screen_name);

            #region Get HomeTimeLine and MentionTimeLine

            //Create base of request.
            //this request will get to 100.
            //this requset is GET Method.
            //When request fail with Http Status Code over 500, it will retry 3 times without exception will be thrown.
            //if you did't call SetIgnoreStatusCodeCondition,thrown exception is intact
            var requestBase =
                OAuthRequest.Create(consumer, accessToken)
                .SetRetryCount(3)
                .SetIgnoreStatusCodeCondition(i => i >= 500)
                .AddParameter(new Parameter(){Key="count",Value="100"})
                .SetHttpMethod(HttpMethodType.Get);

            //Commit HomeTimeLine Request with the base request condition.
            var readyHomeTimeLineRequest =
                 requestBase
                .SetUrl("http://api.twitter.com/1/statuses/home_timeline.xml")
                .CommitRequest();

            //it overwrite RetryCount.
            //If request fail with Http Status Code over 500,it will retrun OAuthResponse that is IsSuccess = false.
            var readyMentionTimeLineRequest =
                requestBase
                .SetRetryCount(0)
                .SetUrl("http://api.twitter.com/1/statuses/mentions.xml")
                .CommitRequest();

            OAuthResponse result1 = readyHomeTimeLineRequest.GetResponse();

            if (result1.IsSuccess)
            {
                //ResponseBody of OAuthResponse can be gotten as string or XElement.
                var result1Text = from s in result1.XElement
                                 .Descendants("status")
                              select
                              s.Element("user").Element("screen_name").Value +
                              " : " +
                              s.Element("text").Value;

                foreach (var s in result1Text)
                {
                    Console.Out.WriteLine(s);
                }
            }

            OAuthResponse result2 = readyMentionTimeLineRequest.GetResponse();

            if (result2.IsSuccess)
            {
                //ResponseBody of OAuthResponse can be gotten as string or XElement.
                var result2Text = from s in result2.XElement
                                 .Descendants("status")
                                  select
                                  s.Element("user").Element("screen_name").Value +
                                  " : " +
                                  s.Element("text").Value;

                foreach (var s in result2Text)
                {
                    Console.Out.WriteLine(s);
                }
            }

            Console.ReadLine();
            #endregion

            #region Tweet (commet out)
            //Console.Out.WriteLine("What's happening ?");

            //string postText = Console.In.ReadLine().TrimEnd('\r', '\n');

            //var res =
            //    OAuthRequest.Create(consumer, accessToken)
            //    .SetHttpMethod(HttpMethodType.Post)
            //    .SetUrl("http://api.twitter.com/1/statuses/update.xml")
            //    .SetRetryCount(3)
            //    .AddParameter(new Parameter() { Key = "status", Value = postText })
            //    .CommitRequest()
            //    .GetResponse();
            #endregion

        }
    }
}
